﻿

$(function () {
    _vmBase = new viewModel();

    _vmBase.init();
})

function viewModel() {
    var me = this;
    VueViewModelBase.call(me);
    viewModelExtend.call(me);


    me.tableListUrl = _getTableListUrl;
    me.addUrl = _updateModelUrl;
    me.delUrl = _deleteModelUrl;
    me.tabObj = $('#tb_roles');
    me.orgTreeUrl = _getTreeDataUrl;

    me.loadedResource;
    me.loadedButtonFunc;
    me.loadedRoleUserTab;
    

    //重写方法
    me.init = function () {


        me.initTableList();

        //添加监听对象
        me.addMonitor();


        me.initRoleAuthoritySplitter();

        me.bindRoleOrg();

        me.bindEventToBtn();

        //初始角色权限，角色菜单，角色用户的按钮禁用状态
        me.setDisabledBtn();
    }

    me.initTableList = function () {
        var options = {
            search: false,
            singleSelect: true,
            columns: [
                {
                    checkbox: true
                },
                {
                    field: 'name',
                    title: '角色名称'

                },
                {
                    field: 'status',
                    title: '状态',
                    filterControl: "select",
                    filterData: "var:_isEnabledSelect",
                    formatter: function (value, row, index) {
                        var enabledLabel = '<span class="label label-success"><i class="fa fa-unlock"></i>' + _enabledStr + '</span>';
                        var disabledLabel = '<span class="label label-default"><i class="fa fa-lock"></i> ' + _disabledStr + '</span>';
                        if (row.status) {
                            return enabledLabel;
                        } else {
                            return disabledLabel;
                        }
                    }
                },
                {
                    field: 'roleRangeName',
                    title: '角色范围'

                },
                {
                    field: 'id',
                    title: '操作',
                    formatter: function (value, row, index) {


                        var enabledEle = '<a href="javascript:void(0)" onclick="_vmBase.onEnabledClick(this,' + index + ',\'' + row.id + '\',\'' + _enabledRoleUrl + '\',\'' + _disabledRoleUrl + '\',event)">' + _enabledStr + '</a>';
                        var disabledEle = '<a href="javascript:void(0)" onclick="_vmBase.onDisabledClick(this,' + index + ',\'' + row.id + '\',\'' + _enabledRoleUrl + '\',\'' + _disabledRoleUrl + '\',event)">' + _disabledStr + '</a>';

                        if (row.status) {
                            return disabledEle;
                        } else if (!row.status) {
                            return enabledEle;
                        }

                    }
                }
            ],
            filterControl: true,
            queryParams: function (params) {
                var filter = "";
                if (params.filter != undefined && params.filter != null) {
                    filter = params.filter;
                }

                var temp = {
                    rows: params.limit,                         //页面大小
                    page: (params.offset / params.limit) + 1,   //页码
                    queryKey: vueModel.queryKey,
                    treeId: vueModel.treeId,
                    filter: filter
                };
                return temp;
            }
        }
        me.initList(options);

    }


    me.setSelectedData = function () {
        var selectRows = me.tabObj.bootstrapTable('getSelections');
        me.selections = selectRows;

        if (selectRows.length <= 0) {
            vueModel.selectedData = false;

            me.setDisabledBtn();
        } else {
            //判断点击的当前行数据是否有效
            var lastSelectObj = selectRows[selectRows.length - 1];
            if (!lastSelectObj.status) {
                vueModel.selectedData = false;

                me.setDisabledBtn();
            } else {
                vueModel.selectedData = true;

                me.setEnabledBtn();
            }


        }
    }

    /*
     * obj 当前操作html对象
     * id  行绑定对象Id
     * opEnableUrl 启用功能url
     * opDisAbleUrl 禁用功能Url
     */
    me.onEnabledClick = function (obj, index, id, opEnableUrl, opDisAbleUrl, e) {
        e.stopPropagation();//行内编辑事件，禁止事件传递（不触发bootstrap table 的clickrow事件）
        $dh.post(opEnableUrl, { id: id }, function (result) {
            if (result.Status == ResultStatus.OK) {
                //刷新
                //vueModel.search();
                $dh.msg("启用成功");

                var disabledEle = '<a href="javascript:void(0)" onclick="_vmBase.onDisabledClick(this,\'' + id + '\',\'' + opEnableUrl + '\',\'' + opDisAbleUrl + '\',event)">' + _disabledStr + '</a>';
                var parentObj = $(obj).parent();
                //parentObj.html("");
                parentObj.html(disabledEle);

                var enabledLabel = '<span class="label label-success" id="' + id + '"><i class="fa fa-unlock"></i>' + _enabledStr + '</span>';
                var parentSb = parentObj.prev();
                parentSb.html(enabledLabel);

                //更新当前行数据
                //选择行，如果当前行数据status 为true,可以启用编辑，角色权限，角色菜单，角色用户 按钮
                me.tabObj.bootstrapTable('updateRow', {
                    index: index,
                    row: {
                        status: true
                    }
                });
            }

        });

    }

    /*
    * obj 当前操作html对象
    * id  行绑定对象Id
    * opEnableUrl 启用功能url
    * opDisAbleUrl 禁用功能Url
    */
    me.onDisabledClick = function (obj, index, id, opEnableUrl, opDisAbleUrl, e) {
        e.stopPropagation(); //行内编辑事件，禁止事件传递（不触发bootstrap table 的clickrow事件）
        $dh.post(opDisAbleUrl, { id: id }, function (result) {
            if (result.Status == ResultStatus.OK) {
                //刷新
                //vueModel.search();
                $dh.msg("禁用成功");

                var enabledEle = '<a href="javascript:void(0)" onclick="_vmBase.onEnabledClick(this,\'' + id + '\',\'' + opEnableUrl + '\',\'' + opDisAbleUrl + '\',event)">' + _enabledStr + '</a>';
                var parentObj = $(obj).parent();
                parentObj.html(enabledEle);

                var disabledLabel = '<span class="label label-default" id="' + id + '"><i class="fa fa-lock"></i> ' + _disabledStr + '</span>';
                var parentSb = parentObj.prev();
                parentSb.html(disabledLabel);

                //更新当前行数据
                me.tabObj.bootstrapTable('updateRow', {
                    index: index,
                    row: {
                        status: false
                    }
                });

            }

        });
    }


    me.save = function (callback) {
        if (!$('#form1').formValid()) {
            return false;
            callback(false);
        }

        var model = vueModel.$data.entityObj;
        
        //执行成功
        $dh.post(me.addUrl, model, function (result) {
            if (result.Status == ResultStatus.OK) {

                callback(result, true);

            } else {
                callback(result, false);

            }
        });
    }

}

function viewModelExtend() {
    var me = this;

    me.addMonitor = function (monitorObj) {
        var targetObj = vueModel.entityObj;

        if (monitorObj != null && monitorObj != undefined) {
            me.addMonitorObj(targetObj, monitorObj);
        } else {
            var addObj = {
                Id: '',
                Name: '',
                Status: true,
                RoleRange: '',
                RoleRangeName: '',
            };
            me.addMonitorObj(targetObj, addObj);
        }
    }

    /**
    角色权限
    */
    //角色权限分配
    me.roleAuthorityAssign = function () {

        _layerIndex = layer.open({
            type: 1,
            title: "角色权限", //不显示标题
            area: ['900px', '600px'], //宽高
            content: $('#roleAuthorityDiv'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
            btn: ['关闭'],
            yes: function () {
                //$dh.msg("关闭");
                if (me.loadedButtonFunc != null && me.loadedButtonFunc != undefined) {
                    me.loadedButtonFunc.bootstrapTable('destroy');
                }
                layer.close(_layerIndex);
            },
            success: function (layero, index) {
                //加载资源
                me.loadResources();
            },
            cancel: function () {
                //$dh.msg("关闭");
                if (me.loadedButtonFunc != null && me.loadedButtonFunc != undefined) {
                    me.loadedButtonFunc.bootstrapTable('destroy');
                }
            }
        });

    }

    //为当前角色加载资源
    me.loadResources = function () {

        if (me.loadedResource != null && me.loadedResource != undefined) {
            me.loadedResource.bootstrapTable('destroy');
        }

        var roleAuthority = $('#tb_roleAuthority').bootstrapTable({
            url: _getRoleResourcesUrl,
            method: 'get',                      //请求方式（*）
            dataType: 'json',
            contentType: "application/x-www-form-urlencoded",
            //toolbar: '#resourceToolBar',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: false,                   //是否显示分页（*）
            singleSelect: true,
            clickToSelect: true,                //是否启用点击选中行
            uniqueId: "Id",                     //每一行的唯一标识，一般为主键列
            detailView: false,                    //显示子表
            columns: [
                {
                checkbox: true

            },
            {
                field: 'name',
                title: '名称',
                filterControl: "input"
            }

            ],
            onClickRow: function (row, $element) {

                var resourceId = row.id;
                
                me.getResourceFuncs(resourceId);

            },
            onCheck: function(row) {
                //var resourceId = row.id;

                //me.getResourceFuncs(resourceId);

            },
            onUncheck: function(row) {
                if (me.loadedButtonFunc != null && me.loadedButtonFunc != undefined) {
                    me.loadedButtonFunc.bootstrapTable('destroy');
                }
            },
            onLoadError: function (status) {
                $dh.RespondStatusCode(status);
            }

        });
        me.loadedResource = roleAuthority;

    }

    //资源功能列表
    me.getResourceFuncs = function (resourceId) {
        if (me.loadedButtonFunc != null && me.loadedButtonFunc != undefined) {
            me.loadedButtonFunc.bootstrapTable('destroy');
        }
        var resourceButtonTab = $('#tb_resourceFuncs').bootstrapTable({
            url: _getResourceFuncsUrl,
            method: 'get',                      //请求方式（*）
            dataType: 'json',
            contentType: "application/x-www-form-urlencoded",
            //toolbar: '',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: false,                   //是否显示分页（*）
            clickToSelect: true,                //是否启用点击选中行
            uniqueId: "FeatrueId",                     //每一行的唯一标识，一般为主键列
            detailView: false,                    //显示子表
            queryParams: function (params) {
                return {
                    resourceId: resourceId
                };
            },
            columns: [{
                checkbox: true

            },
            {
                field: 'featureName',
                title: '功能'
            },{
                field: 'buttonName',
                title: '按钮名称'
                
            },
            {
                field: 'buttonIcon',
                title: '图标',
                formatter: function (value, row, index) {
                    return '<i class="' + row.buttonIcon + '"></i>';
                }
            }
            

            ],
            onCheck: function (row) {
               
            },
            onUncheck: function (row) {
               
            },
            onCheckAll: function (rows) {
               
            },
            onUncheckAll: function (rows) {


            },
            onLoadSuccess: function (data) {

                
                //功能列表加载完毕,加载有权限的功能
                var currentRoleObjs = _vmBase.tabObj.bootstrapTable('getSelections');
                var currentRoleObj = currentRoleObjs[currentRoleObjs.length-1];
                me.getRoleResAuthority(currentRoleObj.id);
            },
            onLoadError: function (status) {
                $dh.RespondStatusCode(status);
            }

        });

        me.loadedButtonFunc = resourceButtonTab;

       
    }

    //保存资源权限
    me.submitResourceAuthority = function () {
        var currentRoleobj = _vmBase.tabObj.bootstrapTable('getSelections');
        var resourceOBjs = $('#tb_roleAuthority').bootstrapTable('getSelections');
        var selectRows = $('#tb_resourceFuncs').bootstrapTable('getSelections');

        var currentRoleId = currentRoleobj[currentRoleobj.length - 1].id;
        var resourceId = resourceOBjs[resourceOBjs.length - 1].id;

        var roleFuncs = [];

        for (var i = 0; i < selectRows.length;i++){

            var roleFuncModel = {};
            roleFuncModel.SubjectId = currentRoleId;
            roleFuncModel.ResourceId = resourceId;
            roleFuncModel.ObjectId = selectRows[i].featrueId;

            roleFuncs.push(roleFuncModel);
        }

        $dh.post(_saveRolePrivilegeUrl, { viewModels: roleFuncs }, function(result) {
            if (result.Status == ResultStatus.OK) {

                $dh.msg("存储成功");

            } else {

                $dh.msg("存储失败");
            }

        });
        
        
        

    }
    //获取角色分配的功能集
    me.getRoleResAuthority = function(roleId) {
        var resourceOBjs = $('#tb_roleAuthority').bootstrapTable('getSelections');
        var resourceId = resourceOBjs[resourceOBjs.length - 1];

        $dh.get(_getRolePrivilegeUrl, { roleId: roleId, resourceId: resourceId }, function(result) {
            var btnIds = [];
            for (var i = 0; i < result.length; i++) {
                btnIds.push(result[i].objectId);

            }

            $("#tb_resourceFuncs").bootstrapTable("checkBy", { field: "featrueId", values: btnIds });
        });
       
    }
   

    //初始化 splitter
    //用childDetailView代替
    me.initRoleAuthoritySplitter = function () {
        $('#roleAuthorityMainSplitter').jqxSplitter({ width: 895, height: 500, panels: [{ size: 300 }] });
    }


     /**
    角色菜单
    */
    //角色菜单分配
    me.roleMenusAssign = function () {
        _roleMenuLayerIndex = layer.open({
            type: 1,
            title: "角色菜单", //不显示标题
            area: ['900px', '600px'], //宽高
            content: $('#roleMenusDiv'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
            btn: ['保存','关闭'],
            yes: function () {
                me.saveMenusForRole();
                //$dh.msg("保存");
            },
            no: function () {
                
                //layer.close(_roleMenuLayerIndex);
            },
            success: function (layero, index) {
                //加载菜单树
                me.loadMenuTree(function (result) {
                    //加载角色菜单
                    me.loadMenusForRole();
                    //setTimeout(function () {
                    //    me.loadMenusForRole();
                    //}, 500);
                    
                });
            },
            cancel: function () {
                
            }
        });
    }

    //获取菜单树
    me.loadMenuTree = function (callback) {
        var setting = {
            view: { selectedMulti: false },
            check: {
                enable: true
            },
            data: {
                key: {
                    name: 'text',
                    title: 'text'
                },
                simpleData: {
                    enable: true,
                    idKey: 'id',
                    pIdKey: 'parentId',
                    rootPId: 'null'
                }
            },
            callback: {
                onClick: function (event, treeId, treeNode) {
                   
                }
            }
        };
        $.getJSON(_getMenuTreeUrl, function (json) {
            var zTreeObj = $.fn.zTree.init($("#roleMenuTree"), setting, json);
            
            //展开所有节点
            zTreeObj.expandAll(true);

            callback(true);
            
        });
    }

    //保存当前角色分配的菜单
    me.saveMenusForRole = function () {
        var treeObj = $.fn.zTree.getZTreeObj("roleMenuTree");
        var nodes = treeObj.getCheckedNodes(true);

        var currentRoleobj = _vmBase.tabObj.bootstrapTable('getSelections');
        var currentRoleId = currentRoleobj[currentRoleobj.length - 1].id;

        var roleMenus = [];
        for (var i = 0; i < nodes.length; i++){
            var roleMenuModel = {};
            roleMenuModel.SubjectId = currentRoleId;
            roleMenuModel.ResourceId = "";
            roleMenuModel.ObjectId = nodes[i].id;

            roleMenus.push(roleMenuModel);
        }

        $dh.post(_saveRoleMenusUrl, { viewModels: roleMenus }, function (result) {
            if (result.Status == ResultStatus.OK) {

                $dh.msg("存储成功");
                layer.close(_roleMenuLayerIndex);

            } else {
                $dh.msg("存储失败");
            }

        });
    }

    //获取当前角色分配的菜单
    me.loadMenusForRole = function () {
        var currentRoleobj = _vmBase.tabObj.bootstrapTable('getSelections');
        var currentRoleId = currentRoleobj[currentRoleobj.length - 1].id;

        var treeObj = $.fn.zTree.getZTreeObj("roleMenuTree");

        $dh.get(_getRoleMenusUrl, { roleId: currentRoleId }, function (result) {

            for (var i = 0; i < result.length;i++){
                
                var rootNode = treeObj.getNodeByParam("id", result[i].objectId, null);

                treeObj.checkNode(rootNode, true, true);
            }

        });

    }


    /**
    角色用户
    */
    //角色用户分配
    me.roleUsersAssign = function () {
        _roleUsersLayerIndex = layer.open({
            type: 1,
            title: "角色用户", //不显示标题
            area: ['900px', '600px'], //宽高
            content: $('#roleUsersDiv'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
            btn: ['关闭'],
            no: function () {
                //layer.close(_roleMenuLayerIndex);
            },
            success: function (layero, index) {
                //加载角色用户
                me.initRoleUsersTable();
            },
            cancel: function () {

            }
        });

    }

    me.initRoleUsersTable = function () {
        if (me.loadedRoleUserTab != null && me.loadedRoleUserTab != undefined) {
            me.loadedRoleUserTab.bootstrapTable('destroy');
        }


        var currentRoleobj = _vmBase.tabObj.bootstrapTable('getSelections');
        var currentRoleId = currentRoleobj[currentRoleobj.length - 1].id;

        var options = {
            search: true,
            searchOnEnterKey: true,
            uniqueId: "Id",
            url: _getRoleUsersUrl,
            toolbar: '#roleUserToolBar',                //工具按钮用哪个容器
            pagination: false,
            clickToSelect: true,
            queryParams: function (params) {
                var temp = {
                    roleId:currentRoleId
                };
                return temp;
            },
            //singleSelect: true,
            columns: [
                {
                    checkbox: true
                },
                {
                    field: 'dH_Account',
                    title: '用户账号'
                },
                {
                    field: 'dH_NickName',
                    title: '用户名'
                }
           
            ]
            
        }
        me.loadedRoleUserTab=$('#tb_roleUsers').bootstrapTable(options);
    }

    me.searchUsers = function () {
        //$dhUsers.init();
        var roleUserDatas = $('#tb_roleUsers').bootstrapTable('getData');
        var userDatas = [];
        for (var i = 0; i < roleUserDatas.length; i++){
            var userid = roleUserDatas[i].id;
            userDatas.push(userid);
        }

        var userDialog = new UserDialog({
            winWidth: '1000px',
            winHeight: '600px',
            userData: userDatas
            
        });
        userDialog.on('confirm', function (result) {
            var aa = result.data;

            //保存角色用户
            me.saveUsersForRole(aa);
        });
    }

    me.saveUsersForRole = function (userIds) {
        var currentRoleobj = _vmBase.tabObj.bootstrapTable('getSelections');
        var currentRoleId = currentRoleobj[currentRoleobj.length - 1].id;

        var roleUsers = [];
        var users = userIds.split(',');
        users = users.hovercUnique(users);//去重

        for (var i = 0; i < users.length; i++) {
            var roleUserModel = {};
            roleUserModel.SubjectId = currentRoleId;
            roleUserModel.ResourceId = "";
            roleUserModel.ObjectId = users[i];
                        
            roleUsers.push(roleUserModel);
            
        }

        $dh.post(_saveRoleUsersUrl, { viewModels: roleUsers }, function (result) {
            if (result.Status == ResultStatus.OK) {
                //刷新表格
                $('#tb_roleUsers').bootstrapTable('refresh');
                

            } else {
                $dh.msg("存储失败");
            }

        });

    }

    me.deleteRoleUsers = function () {
        var currentRoleobj = _vmBase.tabObj.bootstrapTable('getSelections');
        var currentRoleId = currentRoleobj[currentRoleobj.length - 1].id;

        var selectRows = $('#tb_roleUsers').bootstrapTable('getSelections'); 
        var ids = [];
        for (var idIndex = 0; idIndex < selectRows.length; idIndex++) {
            ids.push(selectRows[idIndex].id);
        }
        if (ids.length <= 0) {
            $dh.msg(_SelectADataMsg);
            return;
        }

        $dh.confirm(_deleteRemand, function () {
            //确认删除
            $dh.post(_deleteRoleUserUrl, { roleId: currentRoleId, userids: ids }, function (result) {
                if (result.Status == ResultStatus.OK) {

                    $('#tb_roleUsers').bootstrapTable('refresh');

                } else {
                   
                    $dh.msg("删除失败");
                }
            });

        });
    }


    me.bindRoleOrg = function () {
        $("#RoleRangeName").on("click", function () {
            _roleOrgTree.reload();
        });
        _roleOrgTree = new ParentTreeMultiple(me.orgTreeUrl, "RoleRangeName", "RoleRange", "roleOrg", vueModel.entityObj);

    }

    //初始化按钮事件
    me.bindEventToBtn = function () {
        var btnRolePrivilegeId = "Role_Index_btnRolePrivilege";
        var $pobj = $('#' + btnRolePrivilegeId);
        if ($pobj) {
            var innerHtml = $pobj.html();
            var sliceIndex = innerHtml.indexOf('</i>');
            if (sliceIndex > 0) {
                innerHtml = innerHtml.substr(0, sliceIndex + 4);
                innerHtml += _rolePrivilgeStr;
                $pobj.html(innerHtml);
                $pobj.on("click", me.roleAuthorityAssign);
            }
            
        }

        var btnRoleMenuId = "Role_Index_btnRoleMenu";
        var $mobj = $('#' + btnRoleMenuId);
        if ($mobj) {
            var innerHtml = $mobj.html();
            var sliceIndex = innerHtml.indexOf('</i>');
            if (sliceIndex > 0) {
                innerHtml = innerHtml.substr(0, sliceIndex + 4);
                innerHtml += _roleMenuStr;
                $mobj.html(innerHtml);
                $mobj.on("click", me.roleMenusAssign);
            }
        }

        var btnRoleUserId = "Role_Index_btnRoleUser";
        var $uobj = $('#' + btnRoleUserId);
        if ($uobj) {
            var innerHtml = $uobj.html();
            var sliceIndex = innerHtml.indexOf('</i>');
            if (sliceIndex > 0) {
                innerHtml = innerHtml.substr(0, sliceIndex + 4);
                innerHtml += _roleUserStr;
                $uobj.html(innerHtml);
                $uobj.on("click", me.roleUsersAssign);
            }
        }
        
    }

    //设置角色权限，角色菜单，角色用户的按钮禁用状态
    me.setDisabledBtn = function () {
        var btnRolePrivilegeId = "Role_Index_btnRolePrivilege";
        var $pobj = $('#' + btnRolePrivilegeId);
        $pobj.attr("disabled", true); 

        var btnRoleMenuId = "Role_Index_btnRoleMenu";
        var $mobj = $('#' + btnRoleMenuId);
        $mobj.attr("disabled", true); 

        var btnRoleUserId = "Role_Index_btnRoleUser";
        var $uobj = $('#' + btnRoleUserId);
        $uobj.attr("disabled", true); 
    }
    //设置角色权限，角色菜单，角色用户的按钮启用状态
    me.setEnabledBtn = function () {
        var btnRolePrivilegeId = "Role_Index_btnRolePrivilege";
        var $pobj = $('#' + btnRolePrivilegeId);
        $pobj.attr("disabled", false);

        var btnRoleMenuId = "Role_Index_btnRoleMenu";
        var $mobj = $('#' + btnRoleMenuId);
        $mobj.attr("disabled", false);

        var btnRoleUserId = "Role_Index_btnRoleUser";
        var $uobj = $('#' + btnRoleUserId);
        $uobj.attr("disabled", false); 
    }

}


